package me.jessyan.mvparms.demo.mvp.ui.fragment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.nianlun.libserialport.UsbSerialPortController;
import com.platform.ai.control.R;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.jessyan.mvparms.demo.di.component.DaggerUserComponent;
import me.jessyan.mvparms.demo.di.module.UserModule;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.entity.Device;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import me.jessyan.mvparms.demo.mvp.presenter.UserPresenter;
import me.jessyan.mvparms.demo.mvp.ui.activity.BlueToothActivity;
import me.jessyan.mvparms.demo.mvp.ui.activity.WIFIActivity;
import me.jessyan.mvparms.demo.mvp.ui.adapter.LightMainAdapter;
import me.jessyan.mvparms.demo.mvp.ui.holder.ItemClickListener;
import me.jessyan.mvparms.demo.mvp.ui.receiver.BlueToothReceiver;
import me.jessyan.mvparms.demo.util.USBRsUtils;

import static com.platform.ai.control.R.id.mSwipeRefreshLayout;


@SuppressLint("ValidFragment")
public class ServerFragment extends BaseFragment<UserPresenter> implements UserContract.View, SwipeRefreshLayout.OnRefreshListener, UsbSerialPortController.OnUsbSerialListener {


    @BindView(R.id.rv)
    RecyclerView mRv;

    LightMainAdapter mainAdapter;
    List<Device> mDevices = new ArrayList<>();


    public static ServerFragment newInstance() {
        ServerFragment fragment = new ServerFragment();
        return fragment;
    }

    public ServerFragment(){

    }

    @Override
    public void onResume() {
        super.onResume();
        if(getUserVisibleHint()){
            requestData();
        }
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userModule(new UserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_server, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {


        initRecycleView();
        requestData();
        USBRsUtils.getInstance().init(getActivity(),this);
    }


    public void requestData() {
        mDevices.clear();
        mDevices.add(new Device("勿扰",R.mipmap.icon_disturb,0));
        mDevices.add(new Device("清理",R.mipmap.icon_sweep,0));
//        mDevices.add(new Device("呼叫",R.mipmap.icon_call,0));
//        mDevices.add(new Device("退房",R.mipmap.icon_check,0));
        mDevices.add(new Device("配置WIFI",R.mipmap.icon_wifi,0));
        mDevices.add(new Device("配置蓝牙",R.mipmap.icon_blue_tooth,0));
        mainAdapter.notifyDataSetChanged();

    }

    private void initRecycleView() {
        mainAdapter = new LightMainAdapter(mDevices, new ItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                switch (position){
                    case 0:
                        showMessage("您的勿扰请求已收到，已为您安排");
                        USBRsUtils.getInstance().sendUSBModelCommand(0);
                        break;
                    case 1:
                        showMessage("您的清理请求已收到，已为您安排");
                        USBRsUtils.getInstance().sendUSBModelCommand(1);
                        break;
//                    case 2:
//                        showMessage("您的呼叫请求已收到，已为您安排");
//                        USBRsUtils.getInstance().sendUSBModelCommand(2);
//                        break;
//                    case 3:
//                        new AlertDialog.Builder(getActivity())
//                                .setTitle("提示")
//                                .setMessage("您确定退房吗？")
//                                .setPositiveButton("是", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        showMessage("非常感谢您的入住，欢迎下次光临");
//                                        USBRsUtils.getInstance().sendUSBModelCommand(3);
//                                    }
//                                })
//                                .setNegativeButton("否", null)
//                                .show();
//                        break;
                    case 2:
                        ArmsUtils.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));;
//                        ArmsUtils.startActivity(WIFIActivity.class);
                        break;
                    case 3:
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        try{
                            startActivity(intent);
                        } catch(ActivityNotFoundException ex){
                            ex.printStackTrace();
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
//                        ArmsUtils.startActivity(BlueToothActivity.class);
                        break;
                }
            }
        });
        mRv.setAdapter(mainAdapter);
        ArmsUtils.configRecycleView(mRv, new GridLayoutManager(getContext(),2));


    }

    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {

    }


    @Override
    public void showLoading() {

    }



    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        if (!message.isEmpty()) {
            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void setAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void loginReturn(User user) {

    }

    @Override
    public void logout() {

    }

    public void uploadResult(String string) {

    }

    @Override
    public void onRefresh() {
        requestData();
    }

    @Override
    public void onUsbDeviceStateChange(int usbDeviceState, UsbDevice usbDevice) {

    }

    @Override
    public void onSerialOpenSuccess() {

    }

    @Override
    public void onSerialOpenException(Exception e) {

    }

    @Override
    public void onReceivedData(byte[] data) {

    }

    @Override
    public void onSendException(Exception e) {

    }
}
